<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-row>
						<a-col :span="24">
							<a-form-item label="工厂" v-bind="validateInfos.factoryId">
								<j-search-select :disabled="editDisabled" v-model:value="formData.factoryId" dict="p_factory_manage,name,code"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="产品" v-bind="validateInfos.goodsNo">
								<j-search-select :disabled="editDisabled" v-model:value="formData.goodsNo" :dictOptions="dictOptions"  allow-clear />
							</a-form-item>
						</a-col>
<!--						<a-col :span="24">-->
<!--							<a-form-item label="规格码" v-bind="validateInfos.specNo">-->
<!--                <j-search-select :disabled="editDisabled" v-model:value="formData.specNo" :dict="specCodeDict"  allow-clear />-->
<!--							</a-form-item>-->
<!--						</a-col>-->
						<a-col :span="24">
							<a-form-item label="采购数" v-bind="validateInfos.arrivalNum">
								<a-input-number v-model:value="formData.arrivalNum" placeholder="请输入采购数" style="width: 100%" />
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
import {ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted, watch} from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../ProductOrder.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({}) },
    formBpm: { type: Boolean, default: true }
  });
  const  dictOptions = ref ([]);
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
        factoryId: '',   
        goodsNo: '',
        arrivalNum: undefined,
  });
  const editDisabled =  ref(true);
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    goodsNo: [{ required: true, message: '请输入产品!'},],
    arrivalNum: [{ required: true, message: '请输入采购数!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  const formRef = ref();
  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  // const specCodeDict = ref(`goods_info_spec,spec_no,spec_no`);
  //
  // watch(() => formData.goodsNo, (newGoodsNo) => {
  //   // if (!addDisabled.value) {
  //   //   formData.specNo = null
  //   // }
  //   if (
  //
  //
  //
  //     disabled) {
  //     specCodeDict.value = `goods_info_spec where goods_no = "${newGoodsNo}",spec_no,spec_no`;
  //   }
  //
  //   // console.log(packagingProductRelationTable.columns)
  //   // console.log(packagingProductRelationTable.dataSource)
  // });

  
  /**
   * 新增
   */
  function add() {
    editDisabled.value = false
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      if (tmpData.id) {
        editDisabled.value = true
      }
      //赋值
      Object.assign(formData,tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  watch(() => formData.factoryId, async (newFactoryId) => {
    console.log(newFactoryId)
    await fetchDictOptions(newFactoryId)
    // packagingProductRelationTable.columns[0].options = dictOptions.value
    // console.log('列配置更新后:', packagingProductRelationTable.columns);
    //

  });

  const  fetchDictOptions = async (factoryId) => {

    try {
      // 使用 await 等待异步操作完成
      const res = await defHttp.get({url: `/packaging/factoryProduct/dict?factoryId=`+factoryId,});

      if (res && res.length > 0) {
        dictOptions.value = res.map((item) => ({
          text: item.goodsName,
          value: item.goodsNo,
        }));
      } else {
        dictOptions.value = [];
      }
    }catch (e) {

    }
  };


  defineExpose({
    add,
    edit,
    submitForm,
    fetchDictOptions
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
